//ToDo: create cartouche

var callback = function () {
	//manage callback
	$('div.callback').each(function () {
		$callback = $(this);
		$target = ($callback.attr('target').substr(0,1) == '.') ? $callback.attr('target') : '#' + $callback.attr('target');
		//data is json
		$.ajax({
		  async: false,
		  url: $callback.attr('url') + ($callback.attr('type') ? '/format/' + $callback.attr('type') : ''),
		  dataType:$callback.attr('type'),
		  success: function (message, status) {
				if ($callback.attr('method') == 'clone') {
					//check if data exists
	    			if ($($target).find('div.head').length > 0) {
	    				if ($($target).attr('old-query') != $callback.attr('url')) {
		    				    $clone = $($target).clone();
		    				    _id = $($target).attr('id') + '_' + $('#' +  $($target).attr('id')).length;
		    			 	    $clone.attr('id', _id);
		    				    $clone.html(message);
		    				    $clone.addClass('generic');
		    				    $clone.attr('old-query', $callback.attr('url') + ($callback.attr('type') ? '/format/' + $callback.attr('type') : ''));
						    $clone.insertAfter($target);
						    $('#' + _id).show();
						}
	    				else {
	    					$($target).show();
	    				}
	    			}
	    			else {
	    				$($target).html(message);
	    				$($target).show();
						$($target).attr('old-query', $callback.attr('url') + ($callback.attr('type') ? '/format/' + $callback.attr('type') : ''));
			    	}
	    		}
				else {
					$($target).html(message);
					$($target).show();
					$($target).attr('old-query', $callback.attr('url') + ($callback.attr('type') ? '/format/' + $callback.attr('type') : ''));
		    	}
		  },
		  complete: function () {
			  $callback.remove();
			  $('#toolbox-menu-helper').fadeOut();
			  $('img.reflect').reflect();
			  if ($('div.callback').length > 0) {
				  callback();
			  }
		  },
		  error: function () {
			  // remove it
			  $callback.remove();
		  }
		});
	});
};

$(document).ready(function(e) {
	//callback manager
	callback();
});